class websocket {
  wssUrl: string
  webSocket: WebSocket | null = null
  isConnect: boolean = false // 是否已经连接
  timeoutNumber: number = 1 // 心跳检测间隔
  heartbeatTimer: any = null // 心跳检测定时器
  reconnectTimer: any = null // 断线重连定时器
  isInitiative: boolean = false // 是否主动断开
  againTime: number = 3 // 重连等待时间(单位秒)

  constructor(wssUrl: any) {
    this.wssUrl = wssUrl
    this.initWebSocket()
  }

  initWebSocket() {
    //建立连接
    this.webSocket = new WebSocket(this.wssUrl)
    //连接成功
    this.webSocket.onopen = this.webSocketOnOpen.bind(this)
    //接收信息
    this.webSocket.onmessage = this.webSocketOnMessage.bind(this)
    //连接关闭
    this.webSocket.onclose = this.webSocketOnClose.bind(this)
    //连接错误
    this.webSocket.onerror = this.webSocketOnError.bind(this)
    //心跳检测
    this.heartbeatCheck()
  }

  webSocketOnOpen() {
    this.isConnect = true
    console.log("WebSocket 连接成功")
  }

  webSocketSendMsg() {
    if (this.webSocket?.readyState == 1) {
      this.webSocket.send(JSON.stringify("发送消息"))
    }
  }

  webSocketOnMessage(event: { data: string }) {
    const data = JSON.parse(event.data)
    console.log("data", data)
  }

  webSocketOnClose() {
    console.log("WebSocket 关闭了")
    this.reconnect()
  }

  webSocketOnError(err: any) {
    this.isInitiative = false
    console.log("WebSocket 出错了", err)
  }

  heartbeatCheck() {
    // 心跳检测，检测ws是否正在连接
    this.heartbeatTimer = setInterval(() => {
      this.webSocketSendMsg()
    }, this.timeoutNumber * 1000)
  }

  reconnect() {
    // 停止发送心跳
    clearTimeout(this.reconnectTimer)
    clearInterval(this.heartbeatTimer)
    console.log("reconnect是否人为断开", this.isInitiative)
    // 如果不是人为关闭的话，进行重连
    // if (!this.isInitiative) {
    this.reconnectTimer = setTimeout(() => {
      this.initWebSocket()
    }, this.againTime * 1000)
    // }
  }

  closeWebSocket() {
    this.isInitiative = true
    this.webSocket?.close()
    clearTimeout(this.reconnectTimer)
    clearInterval(this.heartbeatTimer)
    this.webSocket = null
    this.isConnect = false
  }
}

export default websocket
